<template>
  <div id="menuConfiguration">
    <el-card class="box-card">
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <div class="card-header-left">
            <el-icon @click="$router.back()">
              <ArrowLeftBold />
            </el-icon>
            <span>在线热更新</span>
          </div>
        </div>
      </template>
      <!-- 按钮组 -->
      <el-row class="el-col-24">
        <div class="search-form">
          <el-form :inline="true" :model="search" class="searchForm">
            <!-- <el-form-item class="item" style="width: 150px">
              <el-select
                v-model="search.type"
                clearable
                @change="handleSearch"
                de
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  :placeholder="item.name"
                />
              </el-select>
            </el-form-item> -->

            <el-form-item class="item">
              <el-input
                clearable
                v-model="search.search"
                placeholder="请输入版本号进行搜索"
              >
                <template #append>
                  <span
                    class="search"
                    style="cursor: pointer"
                    @click="handleSearch"
                  >
                    搜索
                  </span>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item class="item">
              <el-button type="primary" @click="upLoadClick">上传</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
      >
        <el-table-column prop="version" label="版本" align="center" />
        <el-table-column prop="platform" label="平台" align="center" />
        <el-table-column prop="type" label="当前状态" align="center">
          <template #default="scope">
            <p>{{ scope.row.type == 0 ? '线下' : '线上' }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="addTime" label="时间" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column prop="" label="操作" align="center">
          <template #default="scope">
            <div
              style="
                display: flex;
                flex-direction: row;
                align-items: center;
                gap: 20px;
                cursor: pointer;
              "
            >
              <el-button
                class="curr"
                type="primary"
                @click="handleClick(scope.row, 1)"
              >
                {{ scope.row.type == 0 ? '全网升级' : '测试升级' }}
              </el-button>
              <el-icon><Download @click="handleClick(scope.row, 2)" /></el-icon>
              <el-icon><Delete @click="handleClick(scope.row, 3)" /></el-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="right" style="margin-top: 20px" v-if="search.total">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="search.page"
            v-model:page-size="search.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="search.total"
            @size-change="getProjectsList"
            @current-change="getProjectsList"
          />
        </el-config-provider>
      </div>
    </el-card>
  </div>

  <!-- 上传弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="新增" width="500">
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item label="上传文件" :label-width="formLabelWidth">
        <uploadFiled
          @fileList="fileList"
          :fileType="params"
          ref="uploadFile"
        ></uploadFiled>
      </el-form-item>
      <el-form-item label="平台" prop="platform" :label-width="formLabelWidth">
        <el-select
          v-model="form.platform"
          placeholder="请选择平台"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in customerList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="类型" prop="type" :label-width="formLabelWidth">
        <el-select
          v-model="form.type"
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in typeList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="文件名" prop="name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="策略" prop="strategy" :label-width="formLabelWidth">
        <el-select
          v-model="form.strategy"
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in strategyList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="version" :label-width="formLabelWidth">
        <el-input v-model="form.version" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="remark" :label-width="formLabelWidth">
        <el-input v-model="form.remark" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import uploadFiled from '@/components/qiniuFileUpload';
import SparkMD5 from 'spark-md5'; // 如果是使用 npm 安装的，导入 SparkMD5
import { ref } from 'vue';
// import { useRouter } from 'vue-router';
// import { Search } from '@element-plus/icons-vue';
import {
  // 获取列表
  getVersionList,
  // 新增
  pullVersion,
  // 删除
  deleteVersion,
  // 发布
  save,
} from '@/api/system/versionManage';
import { getCustomerList } from '@/api/appv2/appv2';
import { ElMessage, ElMessageBox } from 'element-plus';
const uploadFile = ref(null);

const customerList = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = '80px';
const form = ref({
  strategy: '1',
});

const rules = {
  platform: [
    {
      required: true,
      message: '请选择平台',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择类型',
      trigger: 'change',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入包名',
      trigger: 'blur',
    },
  ],
  strategy: [
    {
      required: true,
      message: '请输入更新策略',
      trigger: 'blur',
    },
  ],
  version: [
    {
      required: true,
      message: '请输入版本号',
      trigger: 'blur',
    },
  ],
  remark: [
    {
      required: true,
      message: '请输入备注',
      trigger: 'blur',
    },
  ],
};
const ruleFormRef = ref(null);
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('form', form.value);
      if (!form.value.url) {
        ElMessage({
          message: '请上传文件',
          type: 'error',
        });
        return;
      }
      form.value.type = '0';
      pullVersion(form.value).then((res) => {
        if (res.code == 20000) {
          dialogFormVisible.value = false;
          ElMessage({
            message: '提交成功',
            type: 'success',
          });
          getProjectsList();
        } else {
          ElMessage({
            message: '提交失败',
            type: 'error',
          });
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const params = ref({
  typeClass: 1,
  type: '',
  id: '',
  name: '',
  url: '',
  cover: '',
  //   className: '',
  fileSize: '',
  oneTitle: '',
  twoTitle: '',
  // title_One: [],
  title_Two: [],
  fileType: '',
});
const search = ref({
  page: 1,
  pageSize: 10,
  search: '',
  total: 2,
});
// const typeList = ref([
//   { name: '线下', value: '1' },
//   { name: '线上', value: '2' },
// ]);

const strategyList = ref([
  { name: '静默', value: '1' },
  { name: '提示', value: '2' },
  { name: '强制', value: '3' },
]);
// const router = useRouter();

const tableData = ref([]);

// 操作
const handleClick = (row, type) => {
  console.log('row, type:', row, type);
  if (type == 1) {
    const data = {
      id: row.id,
      platform: row.storeId,
      version: row.version,
      type: row.type == 0 ? 1 : 0,
    };
    save(data).then((res) => {
      if (res.code == 20000) {
        ElMessage({
          message: '提交成功',
          type: 'success',
        });
        getProjectsList();
      } else {
        ElMessage({
          message: '提交失败',
          type: 'error',
        });
      }
    });
  } else if (type == 2) {
    const a = document.createElement('a'); // 创建一个 <a> 元素
    a.href = row.url; // 设置下载链接
    a.download = row.name; // 设置下载的文件名
    a.style.display = 'none'; // 隐藏该链接
    document.body.appendChild(a); // 将链接元素添加到 DOM 中
    a.click(); // 模拟点击下载
    document.body.removeChild(a); // 下载完成后移除该元素
  } else if (type == 3) {
    ElMessageBox.confirm('你确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        deleteVersion({ id: row.id }).then((res) => {
          if (res.code == 20000) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            });
            getProjectsList();
          } else {
            ElMessage({
              message: '删除失败',
              type: 'error',
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
        });
      });
  }
};

// 获取列表
const getProjectsList = () => {
  getVersionList(search.value).then((res) => {
    tableData.value = res.data.data;
    search.value.total = res.data.total;
  });
};
getProjectsList();

//搜索
const handleSearch = () => {
  search.value.page = 1;
  getProjectsList();
};

// 点击上传
const upLoadClick = () => {
  console.log('upLoadClick');
  dialogFormVisible.value = true;
  getCustomerListFun(); // 获取机构列表
};

// 上传文件的src
const fileList = ({ response, file }) => {
  console.log('response, file:', response, file);

  // 确保 file 是有效的
  if (!file) {
    console.error('文件无效');
    return;
  }

  const reader = new FileReader();

  // 监听 onload 事件
  reader.onload = (event) => {
    const md5 = new SparkMD5.ArrayBuffer();
    md5.append(event.target.result); // 将文件数据传递给 MD5 计算
    const md5Result = md5.end(); // 获取文件的 MD5 值
    console.log('文件 MD5:', md5Result.toUpperCase());
    // 将 MD5 值存储到某个地方，例如：form.value.md5
    form.value.md5 = md5Result.toUpperCase();

    // 你还可以在这里更新其他的表单数据
    if (response) {
      form.value.url = response.key;
    }
  };

  // 监听 onerror 事件
  reader.onerror = (error) => {
    console.error('文件读取失败:', error);
  };

  // 读取文件为 ArrayBuffer 格式
  reader.readAsArrayBuffer(file.raw);
};

// 获取机构列表
const getCustomerListFun = () => {
  getCustomerList({ page: 1, pageSize: 1000 }).then((res) => {
    customerList.value = res.data.data;
  });
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .card-header-left {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 20px;
    }
  }
}
.curr {
  cursor: pointer;
}
</style>
